package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//定义拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Long empId= (Long) request.getSession().getAttribute("employee");
        log.info("empId:{}",empId);
        if(empId!=null){
            ThreadLocalUtil.setCurrentId(empId);
        }else{
            request.getRequestDispatcher(request.getContextPath()+"/employee/login").forward(request,response);
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return false;
        }
       Long userId=(Long) request.getSession().getAttribute("user");
        if(userId!=null){
            ThreadLocalUtil.setCurrentId(userId);
        }
        return true;
    }
}
